package cn.xiuxius.embedded.runtime.rtx51;

import cn.xiuxius.embedded.EasyStcProjectUtils;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.fileEditor.impl.text.TextEditorProvider;
import com.intellij.openapi.fileEditor.FileEditor;
import com.intellij.openapi.fileEditor.FileEditorProvider;
import com.intellij.openapi.fileEditor.FileEditorPolicy;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.NotNull;

public class TaskSyntaxFileEditorProvider implements FileEditorProvider, DumbAware {

    @Override
    public boolean accept(@NotNull Project project, @NotNull VirtualFile file) {
        boolean type = "c".equalsIgnoreCase(file.getExtension()) || "h".equalsIgnoreCase(file.getExtension()) || "cpp".equalsIgnoreCase(file.getExtension());
        boolean easyStcWithRtx51 = EasyStcProjectUtils.isEasyStcWithRtx51(project);
        return type && easyStcWithRtx51 && EasyStcProjectUtils.containsTaskPattern(file);
    }

    @Override
    public @NotNull FileEditor createEditor(@NotNull Project project, @NotNull VirtualFile file) {

        // 用 TransformedVirtualFile 包装原文件
        TaskTransformedVirtualFile wrappedFile = new TaskTransformedVirtualFile(file);
        Document document = FileDocumentManager.getInstance().getDocument(wrappedFile);
        if (document != null) {
            TaskDocumentListener listener = new TaskDocumentListener(document);
            document.addDocumentListener(listener);
        }
        // 用文本编辑器打开包装后的文件（显示转换后的内容）
        return TextEditorProvider.getInstance().createEditor(project, wrappedFile);
    }

    @Override
    public @NotNull String getEditorTypeId() {
        return "RTX51:TASK:SYNTAX:EDITOR";
    }

    @Override
    public @NotNull FileEditorPolicy getPolicy() {
        return FileEditorPolicy.PLACE_BEFORE_DEFAULT_EDITOR;
    }


}

